package io.renren.modules.device.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.modules.device.entity.DeviceEntity;
import io.renren.modules.device.service.DeviceService;
import io.renren.modules.sys.dao.SysDictDetailDao;
import io.renren.modules.sys.entity.SysDictDetailEntity;
import io.renren.modules.sys.service.SysDictDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.device.dao.DeviceDataDao;
import io.renren.modules.device.entity.DeviceDataEntity;
import io.renren.modules.device.service.DeviceDataService;

import javax.xml.crypto.Data;


@Service("deviceDataService")
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataDao, DeviceDataEntity> implements DeviceDataService {
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private SysDictDetailService sysDictDetailService;

    @Autowired
    private DeviceService deviceService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<DeviceDataEntity> queryWrapper = new QueryWrapper<>();
        if (!params.containsKey("deviceId")) {
            return new PageUtils(new Page<>());
        }
        queryWrapper.eq("device_id", params.get("deviceId"));
        if (params.containsKey("startDate")) {
            queryWrapper.ge("gmt_create", new Date(Long.parseLong((String) params.get("startDate"))));
        }
        if (params.containsKey("endDate")) {
            queryWrapper.le("gmt_create", new Date(Long.parseLong((String) params.get("endDate"))));
        }
        queryWrapper.orderByDesc("id");
        IPage<DeviceDataEntity> page = this.page(
                new Query<DeviceDataEntity>().getPage(params),
                queryWrapper
        );
        checkData(page.getRecords());
        return new PageUtils(page);
    }

    public void checkData(List<DeviceDataEntity> deviceDataEntityList) {
        Iterator<DeviceDataEntity> iterator = deviceDataEntityList.listIterator();
        while (iterator.hasNext()) {
            DeviceDataEntity deviceDataEntity = iterator.next();
            BigDecimal temp = deviceDataEntity.getTemp();
            BigDecimal humi = deviceDataEntity.getHumi();
            BigDecimal temp2 = deviceDataEntity.getTempSecond();
            BigDecimal humi2 = deviceDataEntity.getHumiSecond();
            deviceDataEntity.setHumi(humi2);
            deviceDataEntity.setTemp(temp2);
            deviceDataEntity.setHumiSecond(humi);
            deviceDataEntity.setTempSecond(temp);
//            if (NumberUtil.equals(deviceDataEntity.getHumi(), new BigDecimal(0))
//                    && NumberUtil.equals(deviceDataEntity.getHumiSecond(), new BigDecimal(0))
//                    && NumberUtil.equals(deviceDataEntity.getTemp(), new BigDecimal(-40)) &&
//                    NumberUtil.equals(deviceDataEntity.getTempSecond(), new BigDecimal(-40))) {
//                logger.info("异常数据：" + deviceDataEntity.toString());
//                iterator.remove();
//            }
        }
    }

    @Override
    public int deviceOffline(int seconds, String deviceId) {
        Date now = new Date();
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.SECOND, -seconds);// 默认半小时1800
        Date beforeD = beforeTime.getTime();
        QueryWrapper<DeviceDataEntity> queryWrapper = new QueryWrapper();
        queryWrapper.between("gmt_create", beforeD, new Date()).eq("device_id", deviceId);
        int dataCount = count(queryWrapper);
        return dataCount;
    }

    @Override
    public Map<String, Object> deviceDate(Map<String, Object> params) {
        Map<String, Object> dataMap = new HashMap<>();
        QueryWrapper<DeviceDataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", params.get("deviceId"));
        if (!params.containsKey("deviceId")) {
            return dataMap;
        }
        if (params.containsKey("startDate")) {
            queryWrapper.gt("gmt_create", new Date(Long.parseLong((String) params.get("startDate"))));
        } else {
            Date now = new Date();
            queryWrapper.ge("gmt_create", new Date(now.getTime() - 1000 * 60 * 60 * 24));
        }
        if (params.containsKey("endDate")) {
            queryWrapper.le("gmt_create", new Date(Long.parseLong((String) params.get("endDate"))));
        } else {
            queryWrapper.le("gmt_create", new Date());
        }
        queryWrapper.orderByAsc("id");
        List<DeviceDataEntity> deviceDataEntities = list(queryWrapper);
        List<BigDecimal> temp = new ArrayList<>();
        List<BigDecimal> tempSecond = new ArrayList<>();
        List<BigDecimal> humi = new ArrayList<>();
        List<BigDecimal> humiSecond = new ArrayList<>();
        List<String> xDataList = new ArrayList<>();
        deviceDataEntities.forEach(deviceDataEntity -> {
            temp.add(deviceDataEntity.getTemp());
            tempSecond.add(deviceDataEntity.getTempSecond());
            humi.add(deviceDataEntity.getHumi());
            humiSecond.add(deviceDataEntity.getHumiSecond());
            xDataList.add(DateUtil.format(deviceDataEntity.getGmtCreate(), "HH:mm:ss"));
        });
        DeviceEntity deviceEntity =
                deviceService.getById(Integer.parseInt(params.get("id").toString()));
        QueryWrapper<SysDictDetailEntity> sysDictDetailEntityQueryWrapper = new QueryWrapper<>();
        sysDictDetailEntityQueryWrapper.eq("dict_id", 1);
        sysDictDetailEntityQueryWrapper.eq("value", deviceEntity.getDeviceType());
        List<SysDictDetailEntity> sysDictDetailEntities =
                sysDictDetailService.list(sysDictDetailEntityQueryWrapper);
        List<String> lineNameData = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(sysDictDetailEntities)) {
            JSONObject jsonObject = JSON.parseObject(sysDictDetailEntities.get(0).getConfig());
            lineNameData = jsonObject.getJSONArray("lineNameData").toJavaList(String.class);
        }
        dataMap.put("lineNameData", lineNameData);
        checkChartData(temp,humi);
        checkChartData(tempSecond,humiSecond);
        dataMap.put("tempData", temp);
        dataMap.put("tempDataSecond", tempSecond);
        dataMap.put("humiData", humi);
        dataMap.put("humiSecondData", humiSecond);
        dataMap.put("xDataList", xDataList);
        return dataMap;
    }

    public void checkChartData(List<BigDecimal> tempData, List<BigDecimal> humiData) {
        if (tempData.size() != humiData.size()) {
            return;
        }
        Iterator<BigDecimal> iterator=tempData.iterator();
        Iterator<BigDecimal> iteratorHumi=humiData.iterator();
        while(iterator.hasNext()&&iteratorHumi.hasNext()){
            BigDecimal temp=iterator.next();
            BigDecimal humi=iteratorHumi.next();
            if(NumberUtil.equals(temp, new BigDecimal(-40))
                    && NumberUtil.equals(humi, new BigDecimal(0))){
                iterator.remove();
                iteratorHumi.remove();
            }
        }
    }
}